/**
 * Created by Administrator on 2017-06-12.
 */
var index = {
    init : function(){
        this.sliderH();         //计算左边栏高度
        this.treeTabInit = this.treeTab();          //初始化树切换函数
        this.detailInit = this.detail();            //初始化详情页tab切换
        this.detailGridInit = this.detailGrid();
        this.bind();
        this.ztreeCreat();
        this.initTableData();                       //查询结果表初始化
        this.initSubscribeTable();                  //订阅表初始化
        this.carTree=null;                          // 树对象
        this.vehicleArrayTimer=null;               //订阅定时器 
        this.arrayObj = new Array();
        mapTool.init();
        AMap.plugin(['AMap.ToolBar'],function(){
       	 mapTool.map.addControl(new AMap.ToolBar());
        });
        mapTool.drag({
        	h : 58,
        	callback : function(height){
        		console.log(height);
        		index.myGrid.enableAutoHeight(true,height,true);
        	}
        });
        this.terminalMap = new HashMap();
        this.vehicleMap = new HashMap();
        this.vehicleID=null;
        this.GlobelVehicle = new HashMap();
        this.onlineVehicleStr = null;
        this.trafficLayer=null;
        this.uuidCache=new HashMap();
        this.allNum = new Array();
    	this.runNum = new Array();
      	this.stopNum = new Array();
      	this.droppedNum = new Array();
      	this.vehicleStatus = [0,0,0,0];
      	this.GlobelSubScribeVehicle=new HashMap();
      	this.GlobelSubScribeCommno=new HashMap();
      	this.subScriberTime=this.timer();
      	this.ImgUrlCache = new HashMap();
      	this.myGrid;
      	this.GlobalGpsCache=new HashMap();
      	this.GlobalVehilceNo=new HashMap();
      	this.GlobalAddress = new HashMap();
      	this.GlobalGridField = ['vehicleId','vehicleNo','carStatus','validS','gpsTimeStr','gpsSpeedF','pulseSpeedF','gpsMileageF','status','address'];
    },

    /**
     * 计算各div高度的高度
     * */
    sliderH : function(){
        var winH = $(window).height();
        var sliderH = winH - 42;
        $('.content').css({
            'height' : sliderH + 'px'
        });

        var treeDivH = sliderH - 78 - 225;
        $('.tree-cont').height(treeDivH);

        var mapH = sliderH - 232;
        $('#mymap').height(mapH);

        this.flexigridH = treeDivH-35;
    },

    /**
     * 树切换
     * */
    treeTab : function(){
        var index = 0;
        $('.tree-title-list').click(function(){
            index = $(this).index();
            func(index);
        });
        var func = function(index){
            $('.tree-cont-list').hide().eq(index).show();
            $('.tree-title-line').css({
                left:50 * index + '%'
            });
        };
        var searchFunc = function(eq){
            index = eq;
            func(index);
           
        };
        return {
            searchFunc : searchFunc
        };
    },

    /**
     * 详情内容tab切换
     * */
    detail : function(){
    	var _this = this;
        var index = 0;
        var func = function(index){
            $('.car-details-title-list').removeClass('active').eq(index).addClass('active');
            $('.car-details-cont-list').removeClass('active').eq(index).addClass('active');
            if(index==2){   //当拍照标签click         	
            	if(_this.ImgUrlCache&&_this.ImgUrlCache.containsKey(_this.vehicleID)){
            		$("#photo").attr("src",_this.ImgUrlCache.get(_this.vehicleID));
            		var img = document.getElementById('popimg');
    		        img.setAttribute('src',_this.ImgUrlCache.get(_this.vehicleID));
    		        img.onload = function(){
    		            var width = img.width,
    		                height = img.height;
    		            $('.lager-img').css({
    		                width : width,
    		                height: height, 
    		                'margin-top' : -height/2,
    		                'margin-left' : -width/2
    		            });
    		        }; 
            	}else{
            		$("#photo").attr("src",appCtx+"resources/images/index/phone.jpg");
            		var img = document.getElementById('popimg');
    		        img.setAttribute('src',appCtx+"resources/images/index/phone.jpg");
    		        img.onload = function(){
    		            var width = img.width,
    		                height = img.height;
    		            $('.lager-img').css({
    		                width : width,
    		                height: height,
    		                'margin-top' : -height/2,
    		                'margin-left' : -width/2
    		            });
    		        }; 
            	}
            }
        };
        $('.car-details-title ').on('click','.car-details-title-list',function(){
            index = $(this).index();
            func(index);
        });
        var clickCar= function(eq){
            index = eq;
            func(index);
            
        };
        return {
            clickCar : clickCar,
            index : function(){
                return index;
            }
        }
    },
    /**
     * 订阅tab切换
     * */
    detailGrid : function(){
    	var _this = this;
        var index = 0;
        var func = function(index){
            $('.car-staues-list').removeClass('active').eq(index).addClass('active');
        };
        $('.car-staues-ul').on('click','.car-staues-list',function(){
            index = $(this).index();
            func(index);
            _this.subScribe(_this.arrayObj.toString());
        });
        return {
            index : function(){
                return index;
            }
        }
    },
    /**
     * 查看大图
     * */
    lookBigImg : function(){
        $('.lager-img').show();
        $('#mask').show();
    },

    /**
     * 加载树
     * */
    ztreeCreat : function(){
        var setting = {
            check : {
                enable : true,

                chkboxType : {
                    "Y" : "ps",
                    "N" : "ps"
                }
            },
            data : {
                key : {
                    name : "NAME"
                },
                simpleData : {
                    enable : true,
                    idKey : "ID",
                    pIdKey : "PID",
                    rootPId : 0
                }
            },
            callback : {
                onCheck : index.zTreeOnCheck,
                onClick : index.zTreeOnClick,
                onExpand : index.zTreeOnExpand
            }
        };
        $.ajax({
			type : 'post',
			async : true,
			url : appCtx+"/gis/monitor/getVehicleTree.html",
			cache : false,
			dataType : "JSON",
			success : function(data){
				index.carTree=$.fn.zTree.init($("#carTreeList"), setting, data);
				index.getVehicleStatus(); 
				index.initTerminalMap(data);
			}
		});
        
    },
    /**
     * 车辆id与通信号的缓存
     * @param data
     */
    initTerminalMap : function(data){
    	for(var i=0;i<data.length;i++){
    		if(data[i].TYPE=="2"){
    			index.terminalMap.put(data[i].VID,data[i].CommNO);
    			index.vehicleMap.put(data[i].VID,data[i].NAME);
    			index.GlobelVehicle.put(data[i].VID,data[i]); 
    			index.GlobalVehilceNo.put(data[i].NAME,data[i].VID);
    		}
    	}
    },
    /**
     * 当前用户车辆的上线状态
     */
    getVehicleStatus : function(){
    	var getTimestamp=new Date().getTime();
        var _this = this;
        $.ajax({
            url : appCtx+'gis/monitor/queryVehicleStatus.html?v='+getTimestamp,
            success : function(data){
                if(data){
                	var da = JSON.parse(data);
                    var offline = da.offline;
                    var online = da.online;
                    index.onlineVehicleStr=da.online;
                    var offlineLen = offline.length;
                    var onlineLen = online.length;
                    // 刷新树的图标
                    var getNodes =  $.fn.zTree.getZTreeObj("carTreeList");
                    var nodes = getNodes.transformToArray(getNodes.getNodes());
                    var len = nodes.length;
                    for(var i=0;i<len;i++){
                    	if(nodes[i].iconSkin){
                    		global.vaild();
                    		if(offline.indexOf(nodes[i].VID)>-1){
                    			if(nodes[i].isPublicNet > 0){
                    				nodes[i].iconSkin = 'videoOffline';
                    			}
                        	}else if(online.indexOf(nodes[i].VID)>-1){
                        		if(nodes[i].isPublicNet == 1||nodes[i].isPublicNet == 2||nodes[i].isPublicNet == 3||nodes[i].isPublicNet == 4){
                        			nodes[i].iconSkin = 'videoOnline';
                    			}else{
                    				nodes[i].iconSkin = 'online';        				
                    			}
                        	}
                        	getNodes.updateNode(nodes[i]);
                    	}
                    }
                    //统计 第一级企业在线数
                    var nodes = index.carTree.getNodes();
                    for(var i=0;i<nodes.length;i++){
                    	var vehicles = nodes[i].VehicleCount;
                    	var vehiclesLen = vehicles.length;
                    	var count = 0;
                    	for(var j=0;j<vehiclesLen;j++){
                    		if(global.arr.contains(online,vehicles[j])){
                    			count++;
                    		}
                    	}
                    	nodes[i].NAME = nodes[i].WorkUnitName+"("+count+"/"+nodes[i].VehicleCount.length+")";
                    	getNodes.updateNode(nodes[i])
                    }                
                }else{
                }
            }
        });
        setTimeout(function(){
            _this.getVehicleStatus();
        },180000);
        
	}, 
    /**
     * 查询结果表格
     * */
    initTableData : function(){
        var formmatAction = function (ID,registration_no,vin,terminal_id,isonline){
            var name = vin;
            if(registration_no != "" && registration_no != "undefined" && registration_no != "null"){
                name = name + " (" + registration_no + ")";
            }
            var className = 'isonline_'+isonline + ' ' + 'isonline';
            var colname = '<div id="searchVhicleId_'+ID+'" data-vehicleID="'+ID+'" data-terminal_id="'+terminal_id+'"><span class="'+className+'"></span>'+name+'</div></div>';
            return colname;
        };
        
        $("#vehicleSeachTable").flexigrid({
            dataType : 'json',
            colModel : [{
                display : 'vehicleId',
                name : 'vehicleId',
                width : 10,
                sortable : false,
                hide:true,
                align : 'center'
            },{
                display : '车牌号(自编号)',
                name : 'Handler',
                width : 220,
                sortable : false,
                align : 'left',
                paramcolnames:["vehicleId","internalNumber","registrationNO","terminalId","isonline"],
                handlefunction:formmatAction
            }],
            resizable : false,
            sortname : "vehicleId",// 第一次加载数据时排序列
            sortorder : "desc",// 第一次加载数据时排序类型
            usepager : false,// 是否分页，默认为true。
            showToggleBtn : false,
            showTableToggleBtn : false,// 是否显示收起/打开按钮,默认不显示。
            checkbox : true,// 是否要多选框,默认为false。
            rowId : 'vehicleId',// 多选框绑定行的id,只有checkbox : true时才有效。
            singleSelect : true,
            width : 'auto',// 表格宽度
            height : index.flexigridH, // 表格高度
            titDisplay:false,
            onSuccess : function(data){
            	$("#vehicleSeachTable").find("input[type=checkbox]").each(function() {
					$(this).attr("id","ck_" + $(this).val()).css({"margin-top" : 0});
				}); 	
            },
            onSelectRow : function(data){
            	index.detailInit.clickCar(0);
            	var item = index.GlobelVehicle.get(data.vehicleId);
//                index.loadBaseInfo(item);  // 增加   对右下实时和基础信息的刷新
            	var checked = $("#ck_"+data.vehicleId).attr("checked");
            	var vehicleID = data.vehicleId;
            	var vehileNode = index.carTree.getNodesByParam("VID", vehicleID, null);
            	if (checked) {
            		var vids =$("#vehicleSeachTable").getCheckedRows();
            		var vidsLen = vids.length;
            		for(var i=0;i<vidsLen;i++){
            			if(index.terminalMap.get(vids[i])){
            				index.arrayObj.push(index.terminalMap.get(vids[i]));
            			}	
            		}; 
            		index.arrayObj=global.arr.removeRepeat(index.arrayObj);
            		index.subScribe(index.arrayObj.toString());
            		index.carTree.checkNode(vehileNode, true, true);    // 同步到树
            		if (vehileNode != null && vehileNode.length > 0) {
            			index.carTree.checkNode(vehileNode[0], true, true);
            		}

            	} else {
            		if (vehileNode != null && vehileNode.length > 0) {
            			index.carTree.checkNode(vehileNode[0], false, true);// 同步到树
            			global.arr.removeElm(index.arrayObj,index.terminalMap.get(vehileNode[0].VID));
            			mapTool.clearMarker(vehileNode[0].VID);
            			index.GlobalGpsCache.remove(vehileNode[0].VID);
            		}
            		if(index.arrayObj.length>0){
            			index.subScribe(index.arrayObj.toString());
            		}else{	
            			clearInterval(index.vehicleArrayTimer);
            			index.GlobalGpsCache.clear();
            			index.myGrid.clearAll();
            			index.vehicleStatus=[0,0,0,0];     			
            		}
            		$(".all-num").text(index.vehicleStatus[0]);
             		$(".run-num").text(index.vehicleStatus[1]);
             		$(".stop-num").text(index.vehicleStatus[2]);
             		$(".dropped-num").text(index.vehicleStatus[3]);
            	}
            },
            onSelectAllRow : function(data,checked){
            	var vehicleIds =$("#vehicleSeachTable").getCheckedRows();
            	if(checked){
            		for(var i=0;i<data.length;i++){
            			var vehileNode = index.carTree.getNodesByParam("VID", data[i].vehicleId, null);
            			if(index.terminalMap.get(data[i].vehicleId)){
            				index.arrayObj.push(index.terminalMap.get(data[i].vehicleId));
            			}
            			index.arrayObj=global.arr.removeRepeat(index.arrayObj);
                		index.carTree.checkNode(vehileNode, true, true);    // 同步到树
                		if (vehileNode != null && vehileNode.length > 0) {
                			index.carTree.checkNode(vehileNode[0], true, true);
                		}
            		}
            		index.subScribe(index.arrayObj.toString());
            	}else{
            		for(var i=0;i<data.length;i++){
            			var vehileNode = index.carTree.getNodesByParam("VID", data[i].vehicleId, null);
            			if (vehileNode != null && vehileNode.length > 0) {
                			index.carTree.checkNode(vehileNode[0], false, true);// 同步到树
                			global.arr.removeElm(index.arrayObj,index.terminalMap.get(vehileNode[0].VID));
                			mapTool.clearMarker(vehileNode[0].VID);
                		}
            			if(index.arrayObj.length>0){
                			index.subScribe(index.arrayObj.toString());
                		}else{
                			clearInterval(index.vehicleArrayTimer);
                			index.GlobalGpsCache.clear();
                			index.myGrid.clearAll();
                			index.vehicleStatus=[0,0,0,0];       			
                		}
            			$(".all-num").text(index.vehicleStatus[0]);
                 		$(".run-num").text(index.vehicleStatus[1]);
                 		$(".stop-num").text(index.vehicleStatus[2]);
                 		$(".dropped-num").text(index.vehicleStatus[3]);
            		}
            	}            	
            }
        });
    },
    /**
     *   刷新实时和基础面板
     * @param data
     */
    loadBaseInfo : function(data,grid){  
    	index.resetDetail();
    	var terminalID = data.TID;
    	var CommNO = data.CommNO;
		index.vehicleID=data.VID;
		 $(".car-track").removeAttr("disabled");
		 $(".car-video").removeAttr("disabled");
		 $(".car-workunit").text(data.WNAME);
		 $(".car-num").text(data.NAME);
		 if(data.TNAME){
			 $(".car-vehicleteam").text(data.TNAME); 
		 }
		 if(data.DNAME){
			 $(".car-driver").text(data.DNAME); 
		 }
		 if(data.PHONE){
			 $(".car-car-phone").text(data.PHONE);
		 }
		 if(grid){
			 
		 }else{
			 index.arrayObj.push(CommNO);
			 index.arrayObj=global.arr.removeRepeat(index.arrayObj);
			 index.subScribe(index.arrayObj.toString()); 
		 }	
    },
    /**
     * 初始化订阅表格
     */
    initSubscribeTable : function(){
    	var initOptions = [
        {	// 表格配置
           tableId:'gridbox',
           header:'操作,车牌号,状态,精度,定位时间,速度,脉冲速度,里程,详细信息,位置信息',
           colTypes:'cancelBtn,TrackingBtn,ro,ro,ro,ro,ro,ro,ro,ro',
           code :'Handler,vehicleNo,carStatus,validS,gpsTimeStr,gpsSpeedF,pulseSpeedF,gpsMileageFstatus,address',
           initWidths:'120,120,50,50,125,50,60,50,210,210',
           align:'left,left,left,left,left,left,left,left,left,left'                
    	 }];
    	 var obj = initOptions[0];
    	 index.myGrid = new dhtmlXGridObject(obj.tableId);
         //grid.setImagePath("../imgs/");//设置grid中引用图片路径，如排序图片，checkbox图片，背景等
    	 index.myGrid.setHeader(obj.header);//列标题
    	 index.myGrid.setInitWidths(obj.initWidths);//各列宽度数字表示像素，弹性用*表示
    	 index.myGrid.setColumnIds(obj.code);
    	 index.myGrid.setColAlign(obj.align);//设置列数据的水平布局
    	 index.myGrid.setColTypes(obj.colTypes);//设置列数据的数据类型(ch ---- checkbox; ra ---- radio;ro ---- readonly，双击具体某项数据时不可编辑的;txt ---- 显示的是字符串，双击某项数据会弹出编辑页面 )
    	 index.myGrid.setSkin("dhx_skyblue");//指明使用什么皮肤
    	 index.myGrid.enableAutoHeight(true,221,true);
    	 index.myGrid.init();
    	 index.myGrid.enablePreRendering(30);
    	 index.myGrid.enableSmartRendering(true);  //
    	 index.myGrid.attachEvent("onRowSelect",function(id,ind){
    		var jsonData = index.GlobelSubScribeVehicle.get(id);		
    		if(jsonData){
    			var item = index.GlobelVehicle.get(id);
    			index.loadBaseInfo(item,"grid");
    			mapTool.setCenter(jsonData);
    			index.detailInit.clickCar(0);
    			$(".car-sd").text(jsonData.gpsSpeedF);
	           	$(".car-millage").text(jsonData.gpsMileageF);
	           	$(".car-time").text(jsonData.gpsTimeStr);
	       		$(".car-staue").text(jsonData.status);
	       		$(".car-staue").attr("title",jsonData.status);
	           	var address=mapTool.getAddress("caraddress",jsonData);
	           	if(address){
	           		$("#caraddress").html(address);
	           	}
    		}
    	 });
    },
    /**
     * 订阅（树）
     * @param e
     * @param treeId
     * @param treeNode
     */
    zTreeOnCheck : function(e, treeId, treeNode){
    	if (treeNode.TYPE == 1) {// 企业
    		var terminalList = []; // 
    		var terminal = new HashMap();
    		var childrenNode = index.carTree.transformToArray(treeNode);// 取得所有下级
    		var commnoList =[];
    		var childrenNodeLen = childrenNode.length;
    		if(childrenNodeLen>500&&treeNode.checked){
    			childrenNodeLen=500;
    			global.ajaxLoading.pop("订阅超出500台,只订阅前500台",true,1000);
    		}
    		var start = new Date().getTime();
    		for (var i = 0; i < childrenNodeLen; i++) {
    			if (childrenNode[i].TYPE == 2) {
    				if(treeNode.checked){          //勾选加 terminalID
    					var vehicleID = childrenNode[i].VID;
    					var commNo = childrenNode[i].CommNO;
    					terminal.put(vehicleID,commNo);
        				terminalList.push(terminal);
        				index.arrayObj.push(commNo);
        				$("#ck_"+vehicleID).attr("checked", "checked");
    				}else{              // 取消勾选，清除terminalID    					
    					var vehicleID = childrenNode[i].VID.toString();
    					var commNo = childrenNode[i].CommNO;
    					terminal.put(vehicleID,commNo);
    					terminalList.push(terminal);
    					mapTool.clearMarker(vehicleID);
    					global.arr.removeElm(index.arrayObj,commNo);
    					$("#ck_"+vehicleID).removeAttr("checked");
    					index.GlobalGpsCache.remove(vehicleID);
    				}			
    			}
    		}	
    		if (terminalList.length > 0) {
    			if (treeNode.checked) {
    				index.arrayObj=global.arr.removeRepeat(index.arrayObj);
    				index.subScribe(index.arrayObj.toString());// 订阅
    			} else {
    				index.unSubscribe(terminalList);
    				index.subScribe(index.arrayObj.toString()); //取消之后的重新订阅 
    			}
    		}
    	} else {// 车辆
    		var terminal = new HashMap();
    		var vehicleID = treeNode.VID;
    		var commNo = treeNode.CommNO;
    		terminal.put(vehicleID,commNo);
    		if (treeNode.checked) {
    			index.arrayObj.push(commNo);
    			index.arrayObj=global.arr.removeRepeat(index.arrayObj);
    			index.subScribe(index.arrayObj.toString());
    			$("#ck_"+vehicleID).attr("checked", "checked");
    		} else {
    			index.unSubscribe(commNo);
    			global.arr.removeElm(index.arrayObj,commNo);
    			index.subScribe(index.arrayObj.toString()); //取消之后的重新订阅 
    			$("#ck_"+vehicleID).removeAttr("checked");
    			mapTool.clearMarker(vehicleID);
    			index.GlobalGpsCache.remove(vehicleID);
    		}
    	}
    },
    /**
     * 重置实时和基础信息
     */
    resetDetail : function(){
    	$(".car-num").text("");
   	 	$(".car-sd").text("");
   	 	$(".car-millage").text("");
   	 	$(".car-time").text("");
   	    $(".car-staue").text("");
   	    $(".car-workunit").text("");
   	    $(".car-vehicleteam").text("");
   	    $(".car-driver").text("");
   	    $(".car-car-phone").text("");
   	    $(".car-address").text(""); 	 
    },
    /**
     * 树节点单击，获取实时和基础信息
     * @param e
     * @param treeId
     * @param treeNode
     */
    zTreeOnClick : function(e,treeId, treeNode){
    	index.detailInit.clickCar(0);
    	index.resetDetail();  	
    	var terminalID = treeNode.TID;
    	var CommNO = treeNode.CommNO;
    	if(treeNode.TYPE==2){
    		index.carTree.checkNode(treeNode, true, true);
    		index.vehicleID=treeNode.VID;
    		index.GlobelVehicle.put(treeNode.VID,treeNode);
    		 $(".car-workunit").text(treeNode.WNAME);
    		 $(".car-num").text(treeNode.NAME);
    		 if(treeNode.TNAME){
    			 $(".car-vehicleteam").text(treeNode.WNAME); 
    		 }
    		 if(treeNode.DNAME){
    			 $(".car-driver").text(treeNode.DNAME); 
    		 }
    		 if(treeNode.PHONE){
    			 $(".car-car-phone").text(treeNode.PHONE);
    		 }
    		index.arrayObj.push(CommNO);
 			index.arrayObj=global.arr.removeRepeat(index.arrayObj);
    		index.subScribe(index.arrayObj.toString());
    	};   	
    },
    /**
     * 树节点打开，计算打开企业的上线车
     */
    zTreeOnExpand : function(e, treeId, treeNode){
    	for (var i = 0; i < treeNode.children.length; i++) {
    		var childrenNode = treeNode.children[i];
    		if (childrenNode.TYPE == 1) {// 企业
            	var vehicles = childrenNode.VehicleCount;
            	var count = 0;
            	for(var j=0;j<vehicles.length;j++){
            		if(index.onlineVehicleStr&&global.arr.contains(index.onlineVehicleStr,vehicles[j])){
            			count++;
            		}
            	}
            	childrenNode.NAME = childrenNode.WorkUnitName+"("+count+"/"+childrenNode.VehicleCount.length+")";
            	index.carTree.updateNode(childrenNode);
    		}
    	}
    },
    /**普通查询*/
    searchTable : function(){
        var sarchVal = $.trim($('.search-input').val());
        var paramsGrid = [{
            name : 'keyWord',
            value : sarchVal
        }];
        $("#vehicleSeachTable").flexOptions({
    		url : appCtx+'gis/monitor/queryVehicleByCondition.html',
    		newp : 1,// 设置起始页
    		params : paramsGrid
    	}).flexReload();// 重新加载  
    },
    /**
     * 勾选订阅
     */
    subScribe : function(commnos){
     var getAddressCallback = function(address,jsonData){
    	 if(jsonData == null || !jsonData.hasOwnProperty("vehicleId") ) return;
    		jsonData.address = address;
    		var gpsJson = index.GlobalGpsCache.get(jsonData.vehicleId);
    		if(gpsJson != null){
    			gpsJson.data[index.GlobalGridField.indexOf("address")] = address;
    			index.GlobalGpsCache.put(jsonData.vehicleId,gpsJson);
    		}
    		index.myGrid.cells(jsonData.vehicleId,index.GlobalGridField.indexOf("address")).setValue(address);
    		//{resTime:解析时间（毫秒表示）,address:解析的地址}
    		var obj = {resTime:new Date().getTime(),address:address};
    		index.GlobalAddress.put(jsonData.vehicleId,obj);
     }
   	 var getSubScribeDataVehicles = function(commnos){
   		 var getTimestamp=new Date().getTime();
   		 $.ajax({
              url : appCtx+'gis/monitor/subScribe.html?v='+getTimestamp,
              data : {"commnos":commnos},
              dataType :'json',
              success : function(data){
                  if(data){ 
                	    $("#cancel").css("display","block");
	                  	var vehicleStatus=[0,0,0,0];
	               		vehicleStatus[0]=data.length;
	               		index.allNum=new Array();
	               		index.runNum=new Array();
	               		index.stopNum=new Array();
	               		index.droppedNum=new Array();
	               		index.GlobalGpsCache.clear();
	               		for(var i=0;i<data.length;i++){ 
	               			data[i].vehicleNo=index.vehicleMap.get(data[i].vehicleId);
	               			data[i].internalNumber=index.GlobelVehicle.get(data[i].internalNumber);
	               			if(index.GlobalAddress.get(data[i].vehicleId)){
	               				data[i].address=index.GlobalAddress.get(data[i].vehicleId);
	               			}
	               			mapTool.clearMarker(data[i].vehicleId);
	             			index.addMarker(data[i]);
	             			index.allNum.push(data[i]);
	             			
	               			if(data[i].carStatus==1){
	               				data[i].carStatus="运行";
	               				index.runNum.push(data[i]);
	               				vehicleStatus[1]++;
	               			}else if(data[i].carStatus==2){
	               				data[i].carStatus="停车";
	               				index.stopNum.push(data[i]);
	               				vehicleStatus[2]++;
	               			}else{
	               				data[i].carStatus="掉线";
	               				index.droppedNum.push(data[i]);
	               				vehicleStatus[3]++;
	               			};
	               			
	               			if(data[i].vehicleId==index.vehicleID){
	               				 $(".car-sd").text(data[i].gpsSpeedF);
		                    	 $(".car-millage").text(data[i].gpsMileageF);
		                    	 $(".car-time").text(data[i].gpsTimeStr);
	                    		 $(".car-staue").text(data[i].status);
	                    		 $(".car-staue").attr("title",data[i].status);
		                    	 var address=mapTool.getAddress("caraddress",data[i]);
		                    	 if(address){
		                    		 $("#caraddress").html(address);
		                    	 }
	               			};
	               			if(index.detailGridInit.index()==0){
	               				index.handTrack(data[i]);
	               			}else if(index.detailGridInit.index()==1){
	               				if(data[i].carStatus=="运行"){
	               					index.handTrack(data[i]);
	               				}
	               			}else if(index.detailGridInit.index()==2){
	               				if(data[i].carStatus=="停车"){
	               					index.handTrack(data[i]);
	               				}
	               			}else if(index.detailGridInit.index()==3){
	               				if(data[i].carStatus=="掉线"){               					
	               					index.handTrack(data[i]);
	               				}
	               			}		
	               			index.GlobelSubScribeVehicle.put(data[i].vehicleId,data[i]);
//	               			mapTool.getAddressExtend(null,data[i],getAddressCallback);
	               		}
	               		index.reloadGridData();
	               		$(".all-num").text(vehicleStatus[0]);
	               		$(".run-num").text(vehicleStatus[1]);
	               		$(".stop-num").text(vehicleStatus[2]);
	               		$(".dropped-num").text(vehicleStatus[3]);
                  }else{
	                 	var vehicleStatus=[0,0,0,0];
	                    console.log("no result");
	                    $(".all-num").text(vehicleStatus[0]);
	               		$(".run-num").text(vehicleStatus[1]);
	               		$(".stop-num").text(vehicleStatus[2]);
	               		$(".dropped-num").text(vehicleStatus[3]);
	               		clearInterval(index.vehicleArrayTimer);
                  }
              }
          });
        };
     getSubScribeDataVehicles(commnos);
     clearInterval(index.vehicleArrayTimer);
   	 index.vehicleArrayTimer = setInterval(function(){
   		 getSubScribeDataVehicles(commnos);
   	 },30000);
    },
    /**
     * 取消订阅
     */
    unSubscribe : function(){
    	index.myGrid.clearAll();
    },
    /**
     * 处理定位数据
     */
    handTrack : function(jsonData){
//    	var GlobalGridField = ['vehicleId','vehicleNo','carStatus','validS','gpsTimeStr','gpsSpeedF','pulseSpeedF','gpsMileageF','status','address'];
    	var tmpData = [],tmpValue = null;
    	for(var i = 0; i < index.GlobalGridField.length; i++){
    		tmpValue = jsonData[index.GlobalGridField[i]];

    		if(tmpValue != undefined && tmpValue != null)
    			tmpData.push(tmpValue);
    		else
    			tmpData.push("");
    	}
    	var gridData = {id:jsonData.vehicleId,data:tmpData};
    	index.GlobalGpsCache.put(jsonData.vehicleId,gridData);
    },
    timer : function(){
    	 var subscribetimer;
    	 var funstart = function(){
    		 subscribetimer=setInterval(function(){
        		 index.subScribe();
        	 },20000); 
    	 }
    	 var funend = function(){
    		 clearInterval(subscribetimer);
    	 }
    	 return {
    		 funstart:function(){funstart();},
    		 funend:function(){funend();}
    	}
    	
    },
    /**
     * 导出
     */
    exportExcel : function(){
    	var result = '';
    	if(index.myGrid != undefined){
    		var idArray = index.myGrid.getAllRowIds().split(",");
    		for(var i = 0; i < idArray.length; i++){
    			index.myGrid.forEachCell(idArray[i],function(cellObj,ind){
    				if (ind > 0) {
    					if(1 == ind){
    						var htmls  = cellObj.getValue().match(/>\S+\</);
    						if (htmls!=null) {
    							result += htmls[0].replace(/[<|>]/g,"") + '#';
    						}
    					}else{
    						result += cellObj.getValue() + '#';
    					}
    				}
                });
                result += '&';
            }
    		if(result.length > 0){
    			index.exportExc(appCtx+"gis/monitor/exportExcel.html?time="+ new Date(), {data:result,name:"Monitor"});
    		}else{
    			global.ajaxLoading.pop("暂无数据可导出", true, 2000);
    		}
    	}else{
    		global.ajaxLoading.pop("该表不支持导出!", true, 2000);
    	}
    },
    /**
     * 导出拼装
     * @param url
     * @param params
     */
    exportExc : function(url, params) {    
        var temp = document.createElement("form");        
        temp.action = url;        
        temp.method = "post";        
        temp.style.display = "none";  
        
        var opt1 = document.createElement("input");        
        opt1.name = "name";        
        opt1.value = params.name;
        opt1.type = "hidden";
        temp.appendChild(opt1); 
        
        
        var subLocationArrays = index.getSubParams(params.data);
        for (var i = 0; i < subLocationArrays.length; i++) {        
            var opt = document.createElement("input");        
            opt.name = "subData"+i;        
            opt.value = (subLocationArrays[i]).join("&");        
            temp.appendChild(opt);        
        }   
        document.body.appendChild(temp);   
        temp.submit();        
    },
    /**
     * 导出数据处理
     * @param data
     * @returns {Array}
     */
    getSubParams : function(data) {
    	var locationRows = data.split("&");
    	var i = locationRows.length / 100;
    	var subLocationRows = new Array();
    	for (var j = 0;j < i ; j++) {
    		subLocationRows.push(locationRows.slice(j*100,(j+1)*100));
    	}
    	return subLocationRows;
    },
    /**
     * 指令发送
     */
    sendCommand : function(params){
//    	console.log(params);
    	if(index.vehicleID){
			var data = index.GlobelVehicle.get(index.vehicleID);
			var getTimestamp=new Date().getTime();
			$.ajax({
	               url : appCtx+'gis/monitor/sendCommand.html?v='+getTimestamp,
	               data : {"vehicleId":data.VID,"terminalId":data.TID,"terminalType":data.TerminalType,"commno":data.CommNO,"commandId":params.commandId,"cmdArgs":params.cmdArgs,"commandType":params.commandType},
	               dataType :'json',
	               success : function(item){
	                   if(item.result=="0"){   //  发送成功  获取指令回复
	                	   if(item.flag==0){
	                		   index.uuidCache.put(item.uuid,data);
	                		   index.getCommandReply(item);     		     
	                		   global.ajaxLoading.pop("指令下发到终端",true,1000);
	                	   }else{
	                		   global.ajaxLoading.pop("指令下发失败,原因："+item.resultName,true,1000);
	                	   }    
	                   }else{
	                	   global.ajaxLoading.pop("指令下发超时，未收到终端回执",true,1000);
	                   }
	                   $(".textarea-order").val("");
	               }
	         });
		 }else{
			 global.ajaxLoading.pop("请选择车辆",true,1000);
		 } 	 
    },
    getCommandReply : function(data){
    	if(data){
    		var getTimestamp=new Date().getTime();
    		var params = index.uuidCache.get(data.uuid);
    		$.ajax({
	               url : appCtx+'gis/monitor/getCommandReply.html?v='+getTimestamp,
	               data : {"terminaltype":params.TerminalType,"commno":params.CommNO,"commandId":data.commandId,"cmdPkgSeq":data.cmdPkgSeq,"terminalId":params.TID,"commandTime":data.commandTime,"uuid":data.uuid},
	               dataType :'json',
	               success : function(item){
//	            	   console.log(item);
	                   if(item.result){   //  获取指令回复
	                	   if(item.replyCode=="33536"&&item.uuid==data.uuid){
	                		   global.ajaxLoading.pop("文本下发成功!",true,1000);
	                	   }else if(item.replyCode=="34817"&&item.uuid==data.uuid){
	                		   if(item.imageUrl){
	                			   global.ajaxLoading.pop("拍照成功!",true,1000); 
	                			   $("#photo").attr("src",item.imageUrl);
	                			   if(index.vehicleID==data.vehicleId){
	                				   var img = document.getElementById('popimg');
		                		        img.setAttribute('src',item.imageUrl);
		                		        img.onload = function(){
		                		            var width = img.width,
		                		                height = img.height;
		                		            $('.lager-img').css({
		                		                width : width,
		                		                height: height,
		                		                'margin-top' : -height/2,
		                		                'margin-left' : -width/2
		                		            });
		                		        }; 
	                			   };
	                			   index.ImgUrlCache.put(data.vehicleId,item.imageUrl);
	                		   }else{
	                			   global.ajaxLoading.pop("拍照指令接收超时!",true,1000);
	                		   }  
	                	   }
	                   }else{     // 发送失败 处理
	                	   global.ajaxLoading.pop("接收指令回复超时!",true,1000);
	                   }
	                   $(".textarea-order").val("");
	               }
	         });
    	}
    },
    /**
     * 增加覆盖物
     * @param map
     * @param lon
     * @param lat
     */
	 addMarker : function(data){
		var picUrl = mapTool.getVehicleStatusPicUrl(data.head,data.carStatus);
		var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)}); 
		marker = new AMap.Marker({
	        map: mapTool.map,
	        position: [data.longitude, data.latitude],
	        icon: picUrl,
	        offset: new AMap.Pixel(-15, -10),
	        autoRotation: true
	    });
		marker.on('click', function(e){
			var item = index.GlobelVehicle.get(data.vehicleId);
			index.loadBaseInfo(item);
			mapTool.setCenter(data);
			index.detailInit.clickCar(0);
		});
		mapTool.initHashMap.GlobalMarkerCache.put(data.vehicleId,marker);
	},
	/**
	 * 订阅全部取消
	 */
	cancelAll : function(){
		index.myGrid.clearAll();
		index.GlobalGpsCache.clear();
		index.arrayObj = new Array();
		mapTool.clearAllMarker();
		clearInterval(index.vehicleArrayTimer); 
		$("#cancel").css("display","none");
		index.carTree.checkAllNodes(false);
		$("#ck_*").removeAttr("checked");
		index.vehicleStatus=[0,0,0,0];		
		$(".all-num").text(index.vehicleStatus[0]);
		$(".run-num").text(index.vehicleStatus[1]);
		$(".stop-num").text(index.vehicleStatus[2]);
		$(".dropped-num").text(index.vehicleStatus[3]);	
	},
	/**
	 * 加载订阅表格
	 */
	reloadGridData : function(data){
		index.myGrid.clearAll();
		if(!data){
			data = {
				rows:index.GlobalGpsCache.values()
			};
		}
		index.myGrid.parse(data,"json");
	},
    bind : function(){
		var _this = this;
        //显示更多车辆详情
        $('.car-btn-hide').click(function(){
            if($(this).hasClass('active')){
                $(this).removeClass('active');
                $('.detail-more').hide();
            }else{
                $(this).addClass('active');
                $('.detail-more').show();
            }
        });

        //隐藏更多车辆详情
        $('.close-detail-more').click(function(){
            $('.car-btn-hide').removeClass('active');
            $('.detail-more').hide();
        });

        $('.look-bigimg').click(function(){
            _this.lookBigImg();
        });

        $('.lager-img').find('.close-pop').click(function(){
            $('.lager-img').hide();
            $('#mask').hide();
        });
        
        $('.search-btn').click(function(){
        	var sarchVal = $.trim($('.search-input').val());
        	if(sarchVal){
        		_this.searchTable();
        	}else{
        		global.ajaxLoading.pop("请输入查询关键字",true,1000);
        	}      	
        	_this.treeTabInit.searchFunc(1);
        });
        
        $('.export').find('.icon-export').click(function(){	
        	index.exportExcel();
        });
        
        $('.export').find('.icon-cancel').click(function(){	
        	index.cancelAll();
        });
        
        $('.car-track').click(function(){
        	if(index.vehicleID){
        		if(index.GlobelVehicle.get(index.vehicleID).isPublicNet>0){
        			 var url = appCtx+"video/hisVideo.html?vehicleID="+index.vehicleID;
               		 window.open(url,"_blank");
        		}else{
        			global.ajaxLoading.pop("所选车辆不支持视频",true,1000);
        		}   		
        	}else{
        		global.ajaxLoading.pop("请选择车辆",true,1000);
        	}
   		
        });
	
		 $('.playbackurl').click(function(){
			 if(index.vehicleID){
		   		 var url = appCtx+"gis/playback/trackPlayBack.html?vehicleId="+index.vehicleID;
		   		 window.open(url,"_blank");
			 }else{
				 global.ajaxLoading.pop("请选择车辆",true,1000);
			 };
			 $('.close-detail-more').click();
        });     
		 $('.monitorurl').click(function(){
			 if(index.vehicleID){
		   		 var url = appCtx+"gis/monitor/multiVehicleMonitor.html?vehicleID="+index.vehicleID;
		   		 window.open(url,"_blank");
			 }else{
				 global.ajaxLoading.pop("请选择车辆",true,1000);
			 };
			 $('.close-detail-more').click();
        }); 
		 $('.multivideourl').click(function(){
			 if(index.vehicleID){
		   		 var url = appCtx+"video/videoMonitorMT.html?vehicleID="+index.vehicleID;
		   		 window.open(url,"_blank");
			 }else{
				 global.ajaxLoading.pop("请选择车辆",true,1000);
			 };
			 $('.close-detail-more').click();
        }); 
		 $('.car-video').click(function(){
			 if(index.vehicleID){
				 if(index.GlobelVehicle.get(index.vehicleID).isPublicNet>0){
					 var url = appCtx+"video/videoMonitor.html?vehicleID="+index.vehicleID;
	        		 window.open(url,"_blank");
				 }else{
					 global.ajaxLoading.pop("所选车辆不支持视频",true,1000); 
				 }			  
			 }else{
				 global.ajaxLoading.pop("请选择车辆",true,1000);
			 }   		
         }); 
		 $('.videourl').click(function(){
			 if(index.vehicleID){
				 if(index.GlobelVehicle.get(index.vehicleID).isPublicNet>0){
					 var url = appCtx+"video/videoMonitor.html?vehicleID="+index.vehicleID;
	        		 window.open(url,"_blank"); 
				 }else{
					 global.ajaxLoading.pop("所选车辆不支持视频",true,1000);
				 }			 
			 }else{
				 global.ajaxLoading.pop("请选择车辆",true,1000);
			 };
			 $('.close-detail-more').click();
         });
		 
		 $('.btn-order').click(function(){  //文本下发
			 var params={"commandId":33536,"cmdArgs":"2,1,1,1,1,"+$('.textarea-order').val(),"commandType":"TEXT"};
			 index.sendCommand(params);
		 });
		 $('.phone-btn').click(function(){  //拍照
			 var params={"commandId":34817,"cmdArgs":$('#selectChannel').val()+",1,60,0,"+$('#selectSize').val()+",1,100,100,100,100","commandType":"IMG"};
			 index.sendCommand(params);
		 });
		 
		 $("#listMap").click(function(){
			 var url = appCtx+"gis/matter/logisticsMap.html";
    		 window.open(url,"_blank"); 
		 });
		 
		 $("#mTrafficLi").toggle(function(){
			 index.trafficLayer = new AMap.TileLayer.Traffic({zIndex:10}); //实时路况图层
			 index.trafficLayer.setMap(mapTool.map);
		 },function(){
			 index.trafficLayer.setMap(null);
		 });
		 
		 $("#distanceLi").click(function(){
			  mapTool.map.plugin(["AMap.RangingTool"], function() {
			     ruler = new AMap.RangingTool(mapTool.map);
		         AMap.event.addListener(ruler, "end", function(e) {
		            ruler.turnOff();
		         });
		         ruler.turnOn();
			  });
		 });
		 
		 //显示分享车辆窗口
		 $(".shareVehicleurl").click(function(){
			//var vehicleId=17626;
			var vehicleId=index.vehicleID;
			if(vehicleId){
				$("#shareVehicleId").val(vehicleId);
				 $("#vehicleShareModal").modal("show");
			}
			
			
		 });
		 //获取分享车辆url
		 $("#saveVehicleShareDateBtn").click(function(){
			 index.saveVehicleShareDate();
	    });
     },
     saveVehicleShareDate:function(){
			var inputDate=$("#inputDate").val();
			if(inputDate==""){
				global.ajaxLoading.pop("请选择分享期限！", true, 2000);
				return ;
			}
			var vehicleId=$("#shareVehicleId").val();
			$.ajax({
				type : 'post',
				async : false,
				url : appCtx + "system/vehicle/saveVehicleShareDate.html?vehicleId="+vehicleId+"&inputDate="+$("#inputDate").val(),
				//data:{ids:param},
				cache : false,
				dataType : "JSON",
				success : function(data) {			
					if(data){
						if(data.msg!="成功"){
							global.ajaxLoading.pop(data.msg, true, 2000);
						}else{
							var url=appCtx+"system/vehicle/shareVehicle.html?vehicleId="+data.vehicleIdStr;
							$("#vehicleShareurl_text").html(url);
							$("#vehicleShareurl_text").show();
						}	    			
					}
					
					
				}	
			});	  
		}   	 
};

index.init();
function showVideo(vehicleId){
 	var url = appCtx+"video/videoMonitor.html?vehicleID="+vehicleId;
 	window.open(url,"_blank"); 
};
function showTrack(vehicleId){
	var url = appCtx+"gis/playback/trackPlayBack.html?vehicleId="+vehicleId;
	window.open(url,"_blank");
};
function cancelTrack(vehicleId){
	var vehileNode = index.carTree.getNodesByParam("VID", vehicleId, null);
	index.carTree.checkNode(vehileNode[0], false, true);
	global.arr.removeElm(index.arrayObj,index.terminalMap.get(vehileNode[0].VID));
	mapTool.clearMarker(vehileNode[0].VID);
	index.myGrid.deleteRow(vehileNode[0].VID);
	index.GlobalGpsCache.remove(vehicleId);
	$("#ck_"+vehicleId).removeAttr("checked");
	index.vehicleStatus[0]--;
	if(index.GlobelSubScribeVehicle.get(vehicleId)){
		index.vehicleStatus[index.GlobelSubScribeVehicle.get(vehicleId).carStatus]--;
	}	
	if(index.arrayObj.length>0){
//		index.subScribe(index.arrayObj.toString());
	}else{
		clearInterval(index.vehicleArrayTimer);
		index.GlobalGpsCache.clear();
		index.myGrid.clearAll();
		index.vehicleStatus=[0,0,0,0];		
	}
	$(".all-num").text(index.vehicleStatus[0]);
	$(".run-num").text(index.vehicleStatus[1]);
	$(".stop-num").text(index.vehicleStatus[2]);
	$(".dropped-num").text(index.vehicleStatus[3]);	
}

//自定义列
function eXcell_cancelBtn(cell){
	if(cell){
		this.cell = cell;
		this.grid = this.cell.parentNode.grid;
	}
	this.edit = function(){}
	this.isDisable = function(){return true;}
	this.setValue = function(val){
		var vehicleId = val;
		var handleStr = "";	
		if(index.GlobelVehicle.get(vehicleId).isPublicNet>0){
			handleStr = '<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<img src="'+global.url.domain+'gps-web/resources/images/cancelSub.png" title="取消" onclick="cancelTrack('+vehicleId+')" />'+
							'</div>'+
							'<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<img src="'+global.url.domain+'gps-web/resources/images/video.png" title="视频监控" onclick="showVideo('+vehicleId+')" />'+
							'</div>'+
							'<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<img src="'+global.url.domain+'gps-web/resources/images/track.png" title="轨迹回放" onclick="showTrack('+vehicleId+')" />'+
							'</div>'; 				
		}else{
			handleStr = '<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<img src="'+global.url.domain+'gps-web/resources/images/cancelSub.png" title="取消" onclick="cancelTrack('+vehicleId+')" />'+
							'</div>'+
							'<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<img src="'+global.url.domain+'gps-web/resources/images/track.png" title="轨迹回放" onclick="showTrack('+vehicleId+')" />'+
							'</div>';
		}	
		this.setCValue(handleStr, val);
	}
}
eXcell_cancelBtn.prototype = new eXcell;

//订阅列表
function eXcell_TrackingBtn(cell){
	if(cell){
		this.cell = cell;
		this.grid = this.cell.parentNode.grid;
	}
	this.edit = function(){}
	this.isDisable = function(){return true;}
	this.setValue = function(val){
		this.setCValue('<a href="'+appCtx+'gis/monitor/vehicleMonitor.html?vehicleID='+index.GlobalVehilceNo.get(val)+'" target="_blank" style="color:blue;">'+val+'</a>', val);
	}
}
eXcell_TrackingBtn.prototype = new eXcell;  


